#!/bin/sh
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# Log all calls, with arguments, to /var/log/messages
logger -- "$0" "$@"

. /opt/google/input/xinput.sh

# Determine whether this device has a built-in touchpad by checking
# DEVICES_WITHOUT_BUILT_IN_TOUCHPAD.
check_built_in_touchpad_by_list() {
  BOARD=`grep CHROMEOS_RELEASE_BOARD= /etc/lsb-release | awk -F = '{print $2}'`
  echo "$DEVICES_WITHOUT_BUILT_IN_TOUCHPAD" | grep -v "$BOARD"
}

# Look up if the touchpad default driver conf exists. Note that the touchpad
# default driver conf exists only on a device with a built-in touchpad.
touchpad_default_driver_conf_exists() {
  TOUCHPAD_DEFAULT_DRIVER=touchpad-cmt
  XORG_CONF=/etc/X11/xorg.conf.d
  ls "$XORG_CONF" | grep "$TOUCHPAD_DEFAULT_DRIVER"
}

is_touchpad_builtin() {
  # If the touchpad default driver conf exists, the device definitely has a
  # built-in touchpad.
  # In some rare cases, the touchpad default driver conf may not exist
  # for a short period due to some special reasons. In those cases, we should
  # make sure to update the DEVICES_WITHOUT_BUILT_IN_TOUCHPAD for devices
  # without built-in touchpads.
  touchpad_default_driver_conf_exists || check_built_in_touchpad_by_list
}

# Define the DEVICE state.
# Note that the following device state is not supported yet:
#   TP_PRESENT_NO_TP_EXPECTED
#   NO_TP_PRESENT_TP_EXPECTED_RESUME
#   TP_PRESENT_TP_EXPECTED_RESUME
NO_TP_PRESENT_NO_TP_EXPECTED=0
TP_PRESENT_NO_TP_EXPECTED=1
NO_TP_PRESENT_TP_EXPECTED_BOOT=2
TP_PRESENT_TP_EXPECTED_BOOT=3
NO_TP_PRESENT_TP_EXPECTED_RESUME=4
TP_PRESENT_TP_EXPECTED_RESUME=5
DEVICE_MIN=0
DEVICE_MAX=5
DEVICE_COUNT=$(($DEVICE_MAX - $DEVICE_MIN + 1))

# Probe the touchpad status.
is_touchpad_found() {
  if is_touchpad_builtin; then
    if [ -n "$DEVICE" ]; then
      DEVICE=$TP_PRESENT_TP_EXPECTED_BOOT
    else
      DEVICE=$NO_TP_PRESENT_TP_EXPECTED_BOOT
    fi
  else
    DEVICE=$NO_TP_PRESENT_NO_TP_EXPECTED
  fi
}

# Report the existence of touchpad device
is_touchpad_found
echo $DEVICE > /tmp/input_device_state
metrics_client Touchpad.Device $DEVICE $DEVICE_MIN $DEVICE_MAX $DEVICE_COUNT
